﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Models;

namespace CSMF
{
    public partial class Regist : System.Web.UI.Page
    {

        private UserRegistrationService _registrationService = new UserRegistrationService();
        private AuthenticationService _authenticationService = new AuthenticationService();


        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Reg_Click(object sender, EventArgs e)
        {
            var user = GetGuestCustomer();


            var request = new UserRegistrationRequest()
                              {
                                  Customer = user,
                                  Email = this.EmailText.Text,
                                  Username = this.UserNameText.Text,
                                  IsApproved = true,
                                  Password = this.PasswordText.Text
                              };
            var response = _registrationService.RegisterCustomer(request);
            if(response.Success)
            {
                _authenticationService.SignIn(request.Customer,true); 
                Response.Redirect("index.aspx");

            }
            else
            {
                var error = response.Errors;
                msgLbl.Text = "注册失败: " + error[0];
            }
        }

        private static UserInfo GetGuestCustomer()
        {
            var _workContext = new WebWorkContext();
            var _authenticationService = new AuthenticationService();
            var userService = new UserService();

            if (_workContext.CurrentUser.IsRegistered())
            {
                //Already registered customer. 
                _authenticationService.SignOut();

                //Save a new record
                userService.InsertGuestCustomer();
            }

            var user = _workContext.CurrentUser;
            return user;
        }
    }
}